<script setup>
import { ref , onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useApp } from '@/pinia/modules/app';
import { GetBrandListByPage , AddBrand, UpdateBrand,DeleteBrand } from '@/api/product/brand';
import FileApi from "@/api/product/file";
import { BASE_URL } from "@/utils/request";
import { deepClone } from "@/utils/index";
import { debounce } from '@/utils'

// 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
const headers = {
  token: useApp().authorization.token
}

// 缓存已上传的图片
let oldFiles = []
// 准备删除的旧图片,存储修改前图片的地址,
//if   用户做了修改,删除这些内容,
//else 用户放弃修改,还原这些内容
let oldImg;

//页面数据模版
const list = ref([])

//分页数据总数
const total = ref(0)

//搜索分页对象
const queryDto = ref({
    name:'',
    logo:''
})

//分页默认数据
const pageParamsForm = {
    page:1,
    limit:4
}

const pageParams = ref(pageParamsForm)

onMounted(() => {
    fetchData()
})

const fetchData = async() => {
  console.log('查询页码', pageParams.value.page)
  console.log('查询页码限制', pageParams.value.limit)
  console.log('dto', queryDto.value)

  try {
    const { code, message, data } = await GetBrandListByPage(
      pageParams.value.page,
      pageParams.value.limit,
      queryDto.value
    )

    console.log(data);

    list.value = data.records;
    total.value = data.total;

    console.log('log1',list.value);
    console.log('log',list.value[2].logo);

    console.log('data', data)
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}



const searchBrand = () => {
    fetchData()
}

//重置搜索框
const resetData = () => {
    queryDto.value = {}
    //刷新页面
    fetchData()
}

const debouncedSearchBrand = debounce(searchBrand,300)
const debouncedResetBrand = debounce(resetData,300)

//=======================添加和修改功能====================

const brandForm = {
    id:null,
    name: '',
    logo: null
}


//品牌对象表单数据
const brandDto = ref(brandForm)

const dialogVisible = ref(false)

//深拷贝,打开弹窗
const addShow = () => {
    
    brandDto.value = deepClone(brandForm) //将表单数据深拷贝一份给brandDto,跟第二行虽然同样是置空,但第二行会把属性变成undefined
    //brandDto.value = {}
    dialogVisible.value = true;
}

const saveOrUpdate = () => {
  console.log('品牌名字>>>>>>>>>>>>>>>>>>>>>',brandDto.value.name);
  if (brandDto.value.name === null || brandDto.value.name === '') {  //校验属性非空
    return ElMessage.warning("品牌名称不能为空");
  }
  dialogVisible.value = false;
  if(!brandDto.value.id){
    saveBrand();
  }else{
    doUpdateBrand();
  }
}

const saveBrand = async () => {
    console.log('执行保存操作....',brandDto);
    const { code,message,data } = await AddBrand(brandDto.value)

    console.log(code,message);
    console.log(data);
    if(code===250){
        ElMessage.success('添加品牌成功')
        fetchData()
    }else{
        ElMessage.error('添加品牌失败')
    }

    //多余上传图片删除
    oldFiles.pop() //弹尾
    FileApi.remove(oldFiles) //删除缓存

}

let upload = ref();
// 上传前图片校验
const beforeUpload = (rawFile) => {
  const reg = /\.(gif|jpg|jpeg|png)$/i;  // 使用正则表达式匹配文件后缀名，i表示忽略大小写
  if (!reg.test(rawFile.name)) {  // 使用文件名匹配正则表达式
    ElMessage.warning("图片格式不支持，支持的格式：png/jpg/jpeg/gif");
    return false;
  } else if (rawFile.size > 2 * 1024 * 1024) {  // 文件大小以字节为单位进行比较，2 * 1024 * 1024 表示 2MB
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};

// 图像上传成功以后的事件处理函数
//完成这些: 1.把上传成功返回的图片地址放进缓存数组 2.上传成功之后清除历史记录,确保上传按钮可以多次点击
const handleUploadSuccess = (response, uploadFile) => {

  if (response.code !== 200) return;  //上传成功返回码200,不成功则结束这个方法

  console.log('上传成功钩子返回的数据',response);
  brandDto.value.logo = response.data;
  oldFiles.push(response.data) // 将上传的图片缓存到oldFiles数组，最终调用后端，删除除了最后一张的其他图片
  upload.value.clearFiles(); //上传成功之后清除历史记录
}

//===================品牌更新==========================

//打开弹窗,填充数据
const editShow = (row) => {
  brandDto.value = deepClone(row)

  console.log(brandDto.value);

  //把修改前的图片地址先存起来备用,防止用户放弃修改
  oldImg = brandDto.value.logo

  dialogVisible.value = true;
}

const doUpdateBrand = async () => {
  const {code,message,data} = await UpdateBrand(brandDto.value)
  console.log('更新操作状态码',code);
  console.log('更新操作数据',data);
  if(code===250){
    ElMessage.success('修改成功')
    fetchData();
  }else{
    ElMessage.error('修改失败')
  }

  //删除minio中冗余的图片
  oldFiles.pop() //弹出最后上传的图片地址
  FileApi.remove(oldFiles)  //批量删除多余的图片

}


//用户上传了几张点击了取消
const cancelOperate = () => {
  console.log('damn,用户取消了对话框....');
  //关闭弹窗
  dialogVisible.value = false;
  FileApi.remove(oldFiles);  //删除之前上传的图片,都不要了
}
//用户上传了几张叉掉了对话框
const handleBeforeClose = (damn) => {
  console.log('damn,用户叉掉了对话框,you know M3');
  FileApi.remove(oldFiles);  //删除之前上传的图片,都不要了
  damn();
}


//========================品牌删除功能=========================
const removeBrand = async (row) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?','提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  }).then(async() => {
    brandDto.value = deepClone(row)
    const {code,message,data} = await DeleteBrand(brandDto.value)

    if(code===252){
      ElMessage.success(message)
    }else{
      ElMessage.error(message)
    }

    fetchData();

  })

}


</script>


<template>

    <div class="search-div">
        <!-- 搜索表单 -->
        <el-form label-width="70px" size="small">
        <el-form-item label="关键词">
            <el-input
            v-model.trim="queryDto.name"
            style="width: 100%"
            placeholder="品牌名称"
            ></el-input>
        </el-form-item>
        <el-row style="display:flex">
            <el-button type="primary" size="small" @click="debouncedSearchBrand">
            搜索
            </el-button>
            <el-button size="small" @click="debouncedResetBrand">重置</el-button>
        </el-row>
        </el-form>
    </div>

    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%" 
    :close-on-click-modal="false" 
    :before-close="handleBeforeClose">
        <el-form label-width="120px">
            <el-form-item label="品牌名称">
                <el-input v-model="brandDto.name"/>
            </el-form-item>
            <el-form-item label="品牌图标">
                <el-upload
                        ref="upload"
                        class="avatar-uploader"
                        :action="`${BASE_URL}/admin/product/image/upload`"
                        :show-file-list="false"
                        :limit="1"
                        :on-success="handleUploadSuccess"
                        :on-exceed="handleExceed"
                        :before-upload="beforeUpload"
                        :headers="headers"
                        >
                    <img v-if="brandDto.logo" :src="brandDto.logo" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon el-upload"><Plus/></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="saveOrUpdate">提交</el-button>
                <el-button @click="cancelOperate">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>



    <!--表格数据-->
    <el-table :data="list" style="width: 100%">
            <el-table-column prop="name" label="品牌名称" />
            <el-table-column prop="logo" label="品牌图标" #default="scope">
                <img :src="scope.row.logo" width="50" height="50"/>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" align="center" width="200" #default="scope" >
                <el-button type="primary" size="small" @click="editShow(scope.row)">
                    修改
                </el-button>
                <el-button type="danger" size="small" @click="removeBrand(scope.row)">
                    删除
                </el-button>
            </el-table-column>
    </el-table>

    <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    @size-change="fetchData"
    @current-change="fetchData"
    layout="total, sizes, prev, pager, next"
    :total="total"
    />

</template>


<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 6px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}


.el-icon.avatar-uploader-icon {
  font-size: 22px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}

</style>